<template>
  <el-dialog :title="isEdit?'编辑到达预报':'新增到达预报'"
             :visible.sync="dialogForm"
             width="1200px">
    <el-form :inline="true"
             ref="form"
             :model="form"
             :rules="rules"
             class="add-form"
             label-width="110px">
      <h3>基础信息</h3>
      <hr />
      <br />
      <el-row>
        <el-col :span="8">
          <el-form-item label="货主单位"
                        prop="cargoOwnerId">
            <el-select v-model="form.cargoOwnerId"
                       placeholder="请选择"
                       clearable>
              <el-option v-for="(item,index) in companyList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车船号"
                        prop="transhipNo">
            <el-input type="text"
                      v-model="form.transhipNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输方式"
                        prop="transportWay">
            <el-select v-model="form.transportWay"
                       placeholder="请选择"
                       clearable>
              <el-option v-for="[key,val] in _dictTransportModeType"
                         :key="key"
                         :label="val"
                         :value="key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物资发运时间"
                        prop="startOffDate">
            <el-date-picker v-model="form.startOffDate"
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预计到达时间"
                        prop="forecastArrivalDate">
            <el-date-picker v-model="form.forecastArrivalDate"
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="始发站"
                        prop="startStationCode">
            <el-select v-model="form.startStationCode"
                       placeholder="请选择"
                       @change="selectStation"
                       clearable>
              <el-option v-for="(item,index) in portList"
                         :key="item.id"
                         :label="item.pasName"
                         :value="item.pasCode"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属仓库"
                        prop="warehouseId">
            <el-select v-model="form.warehouseCode"
                       placeholder="请选择"
                       clearable>
              <el-option v-for="(item,index) in warehouseList"
                         :key="index"
                         :label="item.name"
                         :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注"
                        prop="remark">
            <el-input type="text"
                      v-model="form.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <h3>预报明细</h3>
      <hr />
      <el-row class="excel">
        <excel-import code="DDYBMX"
                      @getUploadData="handleImport"></excel-import>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table :data="form.details"
                    border
                    stripe
                    :summary-method="getSummaries"
                    show-summary
                    max-height="550">
            <el-table-column label="序号"
                             min-width="50">
              <template slot-scope="scope">
                {{ scope.$index+1 }}
              </template>
            </el-table-column>
            <el-table-column prop="cargoName"
                             label="品名"
                             min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.cargoName"
                           placeholder="请选择"
                           @change="handleCargoChange('normOneDisabled',scope.row.cargoName)"
                           clearable>
                  <el-option v-for="item in cargoNameList"
                             :key="item.cargoCode"
                             :label="item.cargoName"
                             :value="item.cargoName"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="normOne"
                             label="规格1"
                             min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.normOne"
                           placeholder="请选择"
                           @change="handleCargoChange('normTwoDisabled')"
                           clearable>
                  <el-option v-for="(item,index) in piecesdLIst"
                             :key="index"
                             :label="item.cargoInfo.normOne"
                             :value="item.cargoInfo.normOne"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="normTwo"
                             label="规格2"
                             min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.normTwo"
                           placeholder="请选择"
                           @change="handleCargoChange('normThreeDisabled')"
                           clearable>
                  <el-option v-for="(item,index) in piecesdLIst"
                             :key="index"
                             :label="item.cargoInfo.normTwo"
                             :value="item.cargoInfo.normTwo"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="normThree"
                             label="规格3"
                             min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.normThree"
                           placeholder="请选择"
                           clearable>
                  <el-option v-for="(item,index) in piecesdLIst"
                             :key="index"
                             :label="item.cargoInfo.normThree"
                             :value="item.cargoInfo.normThree"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="material"
                             label="材质"
                             min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.material"
                           placeholder="请选择"
                           @change="handleCargoChange('material')"
                           clearable>
                  <el-option v-for="(item,index) in piecesdLIst"
                             :key="index"
                             :label="item.cargoInfo.material"
                             :value="item.cargoInfo.material"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="madeBy"
                             label="生产厂家"
                             min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.madeBy"
                           placeholder="请选择"
                           @change="handleCargoChange('material')"
                           clearable>
                  <el-option v-for="(item,index) in piecesdLIst"
                             :key="index"
                             :label="item.cargoInfo.madeBy"
                             :value="item.cargoInfo.madeBy"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="baleNo"
                             label="捆包号"
                             min-width="100">
              <template slot-scope="scope">
                <el-input type="text"
                          v-model="scope.row.baleNo"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="num"
                             label="预计件数"
                             min-width="100">
              <template slot-scope="scope">
                <el-input type="text"
                          v-model.number="scope.row.num"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="weight"
                             label="预计重量(吨)"
                             min-width="100">
              <template slot-scope="scope">
                <el-input type="text"
                          v-model.number="scope.row.weight"></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right"
                             align="center"
                             label="操作"
                             width="180">
              <template slot-scope="scope">
                <el-button size="small"
                           type="text"
                           @click="handleAddTable(scope.row)">复制</el-button>
                <el-button :disabled="form.details.length===1"
                           type="text"
                           class="danger"
                           size="small"
                           @click="handleRemove(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer"
         class="dialog-footer">
      <el-button type="primary"
                 @click="handleSubmit"
                 :loading="$store.getters.loadingBtn">保 存</el-button>
      <el-button type="primary"
                 @click="handleSure"
                 v-show="form.transportWay === 'CR'"
                 :loading="$store.getters.loadingBtn">预报确认</el-button>
      <el-button @click="dialogForm = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPiecesCargo } from '@/api/things/accountPageList'
import {
  addArrivalForecast,
  updateArrivalForecast
} from '@/api/enter/arrivalForecast' //始发站
import { getPortList } from '@/api/port/port' //始发站
import { getWarehouseList } from '@/api/adminWarehouse/adminWarehouse' //所属仓库来源于仓库设置
import { getAccountList } from '@/api/commerce/account' //货主单位
import { getCargoNameList } from '@/api/baseResource/baseResource' //品名的下拉菜单
import { getExcelTemplates } from '@/api/excel/index' //下载模板
import autoSearchDic from '@/components/autocomplete/autoSearchDic'
import { exportExcel } from '@/utils/excel-export'
import excelImport from '@/components/excel/import'
import { maxLength, sortLength } from '@/utils/rules'
import { PUBLIC_LIMIT, REG_ALL_NUMBER, PUBLIC_NUMBER_NULL } from '@/utils/Reg'

export default {
  name: 'addArrivalForecastForm',
  components: {
    autoSearchDic,
    excelImport
  },
  data() {
    return {
      form: this.clearForm(),
      condition: {},
      rules: {
        stackPlanTypeDesc: [
          { required: true, validator: PUBLIC_LIMIT, trigger: 'blur' },
          sortLength
        ],
        // orgId: [
        //   { required: true, validator: PUBLIC_LIMIT, trigger: 'blur' },
        //   sortLength
        // ],
        warehouseName: [
          { required: true, message: '请选择所属仓库', trigger: 'blur' }
        ],
        attrCode: [
          { required: true, message: '请选择所属仓库', trigger: 'blur' }
        ],
        priority: [{ validator: PUBLIC_LIMIT, trigger: 'blur' }],
        remark: [maxLength]
      },
      dialogForm: false,
      isEdit: false,
      disabled: false,
      exportExcel: exportExcel,
      principleList: null,
      companyList: null,
      portList: null, //始发站
      cargoNameList: null,
      warehouseList: null,
      normTwoDisabled: true, //规则框禁用
      normOneDisabled: true,
      normThreeDisabled: true,
      otherDisabled: true,
      piecesdLIst: [], //接口获取的货物属性数据
      piecesdatas: {
        //货物属性接口参数
        search_EQ_cargoCode: '',
        search_EQ_cargoName: '',
        search_EQ_material: '',
        search_EQ_measureWay: '',
        search_EQ_normOne: '',
        search_EQ_normThree: '',
        search_EQ_normTwo: ''
      }
    }
  },
  mounted() {
    //获取仓库
    getWarehouseList().then(res => {
      this.warehouseList = res.data.aaData
    })
    //货主单位
    getAccountList().then(res => {
      this.companyList = res.data.aaData
    })
    //品名
    getCargoNameList().then(res => {
      this.cargoNameList = res.data.aaData
    })
    //始发站
    getPortList().then(res => {
      let data = res.data.aaData
      let portList = []
      data.forEach(element => {
        if (element.pasType === 'S') {
          portList.push(element)
        }
      })
      this.portList = portList
    })
  },
  methods: {
    clearForm() {
      return {
        cargoOwnerCode: '',
        cargoOwnerId: null,
        cargoOwnerName: '',
        details: [
          {
            accountNum: null,
            accountWeight: null,
            baleNo: null,
            cargoCode: '',
            cargoName: '',
            madeBy: '',
            material: '',
            normOne: null,
            normThree: null,
            normTwo: null,
            num: null,
            planNum: null,
            weight: null
          }
        ],
        forecastArrivalDate: '',
        forecastNum: 0,
        forecastWeight: 0,
        remark: '',
        startOffDate: '',
        startStationCode: '',
        startStationName: '',
        transhipNo: '',
        transportWay: '',
        type: null
      }
    },
    //复制一行
    handleAddTable(item) {
      let params = { ...item }
      params.sortNo = this.form.details.length + 1
      this.form.details.push(params)
    },
    //删除一行
    handleRemove(index) {
      if (this.form.details.length === 1) {
        this.$message({ message: '至少需要一条数据!', type: 'error' })
      } else {
        this.form.details.splice(index, 1)
      }
    },
    //始发站名称
    selectStation(val) {
      let data = this.portList
      for (let item of data) {
        if (item.pasCode === val) {
          this.form.startStationName = item.pasName
        }
      }
    },
    // 获取货物的name
    // getName(index) {
    //   this.cargoNameList.forEach(element => {
    //     if (this.form.details[index].cargoCode === element.cargoCode) {
    //       this.form.details[index].cargoName = element.cargoName
    //     }
    //     if (this.form.details[index].cargoName === element.cargoName) {
    //       this.form.details[index].cargoCode = element.cargoCode
    //     }
    //   })
    // },
    //导入明细
    handleImport(val) {
      this.form.details = val
    },
    //选择品名，带出规格、材质、生产厂家
    handleCargoChange(status, cargoName) {
      this.form.details.forEach(element => {
        if (element.cargoName) {
          //获取规格1
          for (var i = 0; i < this.cargoNameList.length; i++) {
            if (this.cargoNameList[i].cargoName == element.cargoName) {
              this.piecesdatas.search_EQ_cargoCode = this.cargoNameList[
                i
              ].cargoCode
              this.piecesdatas.search_EQ_cargoName = this.cargoNameList[
                i
              ].cargoName
              this.piecesdatas.search_EQ_madeBy = element.madeBy
              this.piecesdatas.search_EQ_material = element.material
              this.piecesdatas.search_EQ_normOne = element.normOne
              this.piecesdatas.search_EQ_normTwo = element.normTwo
              this.piecesdatas.search_EQ_normThree = element.normThree
              this.$nextTick(function() {
                switch (status) {
                  case 'normOneDisabled':
                    // element.cargoCode = ''
                    // element.cargoId = ''
                    this.piecesdatas.search_EQ_cargoName = element.cargoName
                    this.piecesdatas.search_EQ_madeBy = ''
                    element.madeBy = ''
                    this.piecesdatas.search_EQ_material = ''
                    element.material = ''
                    this.piecesdatas.search_EQ_normOne = ''
                    element.normOne = ''
                    this.piecesdatas.search_EQ_normTwo = ''
                    element.normTwo = ''
                    this.piecesdatas.search_EQ_normThree = ''
                    element.normThree = ''
                    break
                  default:
                    console.log('其他')
                }
                this.getPiecesCargoApi(cargoName)
              })
            }
          }
        } else {
          // element.cargoName = ''
          this.piecesdatas.search_EQ_madeBy = ''
          element.madeBy = ''
          this.piecesdatas.search_EQ_material = ''
          element.material = ''
          this.piecesdatas.search_EQ_normOne = ''
          element.normOne = ''
          this.piecesdatas.search_EQ_normTwo = ''
          element.normTwo = ''
          this.piecesdatas.search_EQ_normThree = ''
          element.normThree = ''
        }
      })
    },
    getPiecesCargoApi(cargoName) {
      console.log('cargoName', cargoName)
      // let pam = this.filterPamars(this.piecesdatas)
      // console.log('pam', pam)
      // console.log('this.piecesdatas', this.piecesdatas)
      let cargoCode
      this.cargoNameList.forEach(element => {
        if (element.cargoName === cargoName) {
          cargoCode = element.cargoCode
        }
      })
      console.log('cargoCode', cargoCode)
      getPiecesCargo({
        search_EQ_cargoCode: cargoCode,
        search_EQ_cargoName: cargoName
      }).then(res => {
        this.piecesdLIst = res.data.aaData
        console.log('piecesdLIst', res.data.aaData)
        if (this.piecesdLIst.length == 1) {
          this.form.details.forEach(element => {
            // element.cargoId = this.piecesdLIst[0].id
            this.piecesdatas.search_EQ_cargoCode = this.piecesdLIst[0].cargoInfo.cargoCode
            element.cargoCode = this.piecesdLIst[0].cargoInfo.cargoCode
            this.piecesdatas.search_EQ_cargoName = this.piecesdLIst[0].cargoInfo.cargoName
            element.cargoName = this.piecesdLIst[0].cargoInfo.cargoName
            this.piecesdatas.search_EQ_madeBy = this.piecesdLIst[0].cargoInfo.madeBy
            element.madeBy = this.piecesdLIst[0].cargoInfo.madeBy
            this.piecesdatas.search_EQ_material = this.piecesdLIst[0].cargoInfo.material
            element.material = this.piecesdLIst[0].cargoInfo.material
            this.piecesdatas.search_EQ_normOne = this.piecesdLIst[0].cargoInfo.normOne
            element.normOne = this.piecesdLIst[0].cargoInfo.normOne
            this.piecesdatas.search_EQ_normTwo = this.piecesdLIst[0].cargoInfo.normTwo
            element.normTwo = this.piecesdLIst[0].cargoInfo.normTwo
            this.piecesdatas.search_EQ_normThree = this.piecesdLIst[0].cargoInfo.normThree
            element.normThree = this.piecesdLIst[0].cargoInfo.normThree
            // this.otherDisabled = false
            // this.normOneDisabled = false
            // this.normTwoDisabled = false
            // this.normThreeDisabled = false
          })
          return false
        }
      })
    },
    filterPamars(param) {
      let pam = {}
      for (let i in param) {
        if (param[i] != '') {
          pam[i] = param[i]
        }
      }
      return pam
    },
    // 保存
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.handleToEdit() : this.handleToAdd()
        } else {
          this.$message({
            message: '请检查表单',
            type: 'error'
          })
        }
      })
    },
    // 新增
    handleToAdd() {
      this.form.type = 1
      // let data = this.form.details
      // this.form.details.forEach(element => {
      //   this.cargoNameList.forEach(item => {
      //     if(element.cargoName === item.cargoName)

      //   })
      //   element.cargoName
      // })
      addArrivalForecast(this.form).then(res => {
        this.$message({ message: '新增成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    // 编辑
    handleToEdit() {
      this.form.type = 1
      updateArrivalForecast(this.form.entrustNo, this.form).then(res => {
        this.$message({ message: '编辑成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    // 预报确认
    handleSure() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.handleToEditSure() : this.handleToAddSure()
        } else {
          this.$message({
            message: '请检查表单',
            type: 'error'
          })
        }
      })
    },
    // 新增：预报确认
    handleToAddSure() {
      this.form.type = 2
      addArrivalForecast(this.form).then(res => {
        this.$message({ message: '预报确认成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    // 编辑：预报确认
    handleToEditSure() {
      this.form.type = 2
      updateArrivalForecast(this.form.entrustNo, this.form).then(res => {
        this.$message({ message: '预报确认成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (column.property === 'weight') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 吨'
        } else if (column.property === 'num') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ' 件'
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  },
  watch: {
    dialogForm(bool) {
      if (!bool) {
        this.$refs.form.resetFields()
        this.isEdit = false
        this.form = this.clearForm()
        this.$emit('clear')
      } else {
        if (this.form.cargoName) {
          this.otherDisabled = false
          this.normOneDisabled = false
          this.normTwoDisabled = false
          this.normThreeDisabled = false
        }
      }
    }
  }
}
</script>

<style scoped>
.excel {
  margin: 10px 0;
}
</style>
